package guoanmaker.operator.business.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import guoanmaker.operator.business.model.OperatorActivityEnlist;
import guoanmaker.operator.business.model.OperatorEventDetails;
import guoanmaker.operator.business.model.OperatorLuckdrawRecord;
import guoanmaker.operator.business.model.OperatorUser;
import guoanmaker.operator.business.model.PersonalUser;
import guoanmaker.operator.business.model.ProvideCity;
import guoanmaker.operator.business.model.ProviderProvince;
import guoanmaker.operator.business.modelnobind.CommodityMove;
import guoanmaker.operator.business.modelnobind.EventDetailsMove;
import guoanmaker.operator.business.modelnobind.LuckdrawRecordAndCoupons;
import guoanmaker.operator.business.modelnobind.LuckdrawRecordMove;
import guoanmaker.operator.business.modelnobind.operatorEnlistDetails;
import guoanmaker.operator.business.repository.OperatorEventDetailsRepository;
import guoanmaker.operator.business.repository.OperatorLuckdrawRecordRepository;
import guoanmaker.operator.business.repository.OperatorUserRepository;
import guoanmaker.operator.business.repository.PersonalUserRepository;
import guoanmaker.operator.business.repository.ProvideCityRepository;
import guoanmaker.operator.business.repository.ProviderProvinceRepository;

@Repository
public class OperatorEventDetailsDao {

	@PersistenceContext
	EntityManager manager;

	@Autowired
	private OperatorUserRepository operatorUserRepository;
	@Autowired
	private ProviderProvinceRepository providerProvinceRepository;
	@Autowired
	private OperatorEventDetailsRepository operatorEventDetailsRepository;
	@Autowired
	private ProvideCityRepository provideCityRepository;
	@Autowired
	private OperatorLuckdrawRecordRepository operatorLuckdrawRecordRepository;
	@Autowired
	private PersonalUserRepository personalUserRepository;

	public Integer getEventJoinPersonNums(String id, String ActivityTypeId) {
		if (!ActivityTypeId.equals("抽奖")) {
			String jpql = "SELECT sum(e.buyNum) FROM OperatorEventDetails s,OperatorActivityEnlist e WHERE s.id = :id  AND s.state <> 4 AND e.activityId = s.id AND e.state = 1";
			Query createQuery = manager.createQuery(jpql);
			createQuery.setParameter("id", id);
			Long singleResult = (Long) createQuery.getSingleResult();
			manager.clear();
			if (singleResult == null) {
				return 0;
			} else {
				return singleResult.intValue();
			}

		} else {
			Integer item = 0;
			item = operatorLuckdrawRecordRepository.selectByActivityId(id);
			if (item == null) {
				item = 0;
			}
			return item;
		}
	}

	// 通过活动类型id查询活动详情
	public Map<String, Object> getEventById(String id, Integer page, Integer size) {
		String jpql = "select  s from  OperatorEventDetails s  where s.eventType = 1 and s.activityTypeId='" + id
				+ "' and  s.state <> 4 and s.state <> 0";
		Query createQuery = manager.createQuery(jpql);
		Map<String, Object> map = new HashMap<>();
		int index = (page - 1) * size;// 计算开始的记录数
		if (createQuery.getResultList().size() != 0) {
			map.put("size", createQuery.getResultList().size());
		}
		@SuppressWarnings("unchecked")
		List<OperatorEventDetails> enlistlist = createQuery.setMaxResults(size).setFirstResult(index).getResultList();
		if (enlistlist.size() > 0) {
			for (OperatorEventDetails OperatorEventDetails : enlistlist) {
				if (OperatorEventDetails.getFounder() != null) {
					OperatorUser user = operatorUserRepository.findOne(OperatorEventDetails.getFounder());
					if (user != null) {
						OperatorEventDetails.setName(user.getName());
					}
				}
				if (OperatorEventDetails.getEventPlace() != null && !OperatorEventDetails.getEventPlace().equals("")) {
					ProviderProvince providerProvince = providerProvinceRepository
							.findOne(OperatorEventDetails.getEventPlace());
					if (providerProvince != null) {
						OperatorEventDetails.setPname(providerProvince.getName());
					}
				}
				if (OperatorEventDetails.getEventCounty() != null
						&& !OperatorEventDetails.getEventCounty().equals("")) {
					ProvideCity ProvideCity = provideCityRepository.findOne(OperatorEventDetails.getEventCounty());
					if (ProvideCity.getName() != null) {
						OperatorEventDetails.setAname(ProvideCity.getName());
					}
				}
			}
		}
		map.put("cuont", enlistlist);
		manager.clear();// 分离内存中受EntityManager管理的实体bean，让VM进行垃圾回收
		return map;
	}

	// 通过id查询活动详情
	public OperatorEventDetails getSelectEvent(String id) {
		OperatorEventDetails OperatorEventDetails = operatorEventDetailsRepository.getSelectEventByid(id);
		if (OperatorEventDetails != null) {
			if (OperatorEventDetails.getFounder() != null) {
				OperatorUser user = operatorUserRepository.findOne(OperatorEventDetails.getFounder());
				if (user != null) {
					OperatorEventDetails.setName(user.getName());
				}
			}
			if (OperatorEventDetails.getEventPlace() != null && !OperatorEventDetails.getEventPlace().equals("")) {
				ProviderProvince providerProvince = providerProvinceRepository
						.findOne(OperatorEventDetails.getEventPlace());
				if (providerProvince != null) {
					OperatorEventDetails.setPname(providerProvince.getName());
				}
			}
			if (OperatorEventDetails.getEventCounty() != null && !OperatorEventDetails.getEventCounty().equals("")) {
				ProvideCity findOne = provideCityRepository.findOne(OperatorEventDetails.getEventCounty());
				if (findOne.getName() != null) {
					OperatorEventDetails.setAname(findOne.getName());
				}
			}
		}
		return OperatorEventDetails;
	}

	// 查询线上下线所有活动
	@SuppressWarnings("unchecked")
	public Map<String, Object> getAllOperatorEventDetails(Integer eventType, Integer page, Integer size) {
		String jpql = "select s from  OperatorEventDetails s where s.eventType=:eventType and s.state <> 4 order by s.weight asc";
		Query query = manager.createQuery(jpql);
		Map<String, Object> map = new HashMap<>();
		int index = (page - 1) * size;// 计算开始的记录数
		query = query.setParameter("eventType", eventType);
		if (query.getResultList().size() != 0) {
			map.put("size", query.getResultList().size());
		}
		Date date = new Date();
		List<OperatorEventDetails> operatorEventDetails = query.setMaxResults(size).setFirstResult(index)
				.getResultList();
		Long nowTime= new Date().getTime();//获取当前时间
		for (OperatorEventDetails eventDetails : operatorEventDetails) {
			if (eventDetails.getAvailability() == 1) {
			    Integer orgstate =eventDetails.getState();
			    // 0未发布 默认 状态  7是未生效  4 是已删除
			    //报名未开始   6  报名时间 不为空   于 当前时间  并且 原状态 是 未发布 0 状态 
				if(eventDetails.getSignupStartTime() !=null && eventDetails.getSignupStartTime().getTime()>nowTime && eventDetails.getReleaseTime().getTime()< nowTime && orgstate ==0){
					operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),6);
				}
				//报名中  5   报名时间 不为空    报名开始时间  <=当前时间  <结束时间   且 原状态为  报名未开始 6 状态 
				else if(eventDetails.getSignupStartTime() !=null && eventDetails.getSignupStartTime().getTime()<=nowTime && eventDetails.getSignupEndTime().getTime()>nowTime && orgstate== 6 ){
					operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),5);
				}
				//未开始   1 活动开始时间 不能为空       开始时间 > 当前时间      发布时间 <=现在时间   原状态 为 报名中 5 
				else if(eventDetails.getEventStartTime() !=null && eventDetails.getSignupStartTime() !=null && eventDetails.getEventStartTime().getTime() >nowTime && eventDetails.getSignupEndTime().getTime() <nowTime && eventDetails.getReleaseTime().getTime() <=nowTime && orgstate== 5  ){
					operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),1);
				}
				//未开始   1 活动开始时间 不能为空       开始时间 > 当前时间      发布时间 <=现在时间   原状态 为 0未发布
				else if(eventDetails.getEventStartTime() !=null   && eventDetails.getSignupStartTime() ==null && eventDetails.getEventStartTime().getTime() >nowTime && eventDetails.getReleaseTime().getTime() <=nowTime && orgstate== 0 ){
					operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),1);
				}
				//活动开始 2   活动开始时间 不能为空    活动开始时间<= 当前时间 <结束时间    且 原状态 为 未开始 1 状态 
				else if(eventDetails.getEventStartTime() !=null && eventDetails.getEventStartTime().getTime()<=nowTime && eventDetails.getEventEndTime().getTime()>nowTime &&(orgstate==1 )){
					operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),2);
				}
				//活动结束 3   活动结束 时间 不能为空    活动结束 时间 < 当前时间   且 原状态 为 开始2  状态 
				else if(eventDetails.getEventEndTime() !=null && eventDetails.getEventEndTime().getTime()< nowTime &&(orgstate==2)){
					operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),3);
				}
			}
		/*	// 如果未点击是否生效就修改活动状态为为生效状态
			if (operatorEventDetails2.getAvailability() == 0) {
				operatorEventDetailsRepository.updateEventStateSeven(operatorEventDetails2.getId());
				operatorEventDetails2.setState(7);
			} else {
				// 如果当前时间大于等于发布时间就修改活动状态
				if (date.getTime() >= operatorEventDetails2.getReleaseTime().getTime()) {
					if (!operatorEventDetails2.getActivityTypeId().equals("抽奖")) {
						if(operatorEventDetails2.getAgreeOrNot() == 1){
							if(operatorEventDetails2.getSignupStartTime()!=null){
								// 当前时间小于活动活动报名时间 -- 报名未开始
								if (date.getTime() < operatorEventDetails2.getSignupStartTime().getTime()) {
									operatorEventDetailsRepository.updateEventStateSix(operatorEventDetails2.getId());
									operatorEventDetails2.setState(6);
								}
								
								// 当前时间大于等于活动活动报名时间 -- 报名开始
								if (date.getTime() >= operatorEventDetails2.getSignupStartTime().getTime()) {
									operatorEventDetailsRepository.updateEventStateFive(operatorEventDetails2.getId());
									operatorEventDetails2.setState(5);
								}
								
								// 当前时间大于活动报名时间 如果活动开始时间小于当前时间--活动未开始
								if (date.getTime() >= operatorEventDetails2.getSignupEndTime().getTime()
										&& date.getTime() <= operatorEventDetails2.getEventStartTime().getTime()) {
									operatorEventDetailsRepository.updateEventStarteOne(operatorEventDetails2.getId());
									operatorEventDetails2.setState(1);
								}
								// 如果活动开始时间大于当前时间--活动已开始
								if (date.getTime() >= operatorEventDetails2.getSignupEndTime().getTime()
										&& date.getTime() >= operatorEventDetails2.getEventStartTime().getTime()) {
									operatorEventDetailsRepository.updateEventStateTwo(operatorEventDetails2.getId());
									operatorEventDetails2.setState(2);
								}
								// 如果活动结束时间大于当前时间--活动结束
								if (date.getTime() >= operatorEventDetails2.getSignupEndTime().getTime()
										&& date.getTime() >= operatorEventDetails2.getEventEndTime().getTime()) {
									operatorEventDetailsRepository.updateEventEndTimeState(operatorEventDetails2.getId());
									operatorEventDetails2.setState(3);
								}
							}
							
						}else{
							if (date.getTime() <= operatorEventDetails2.getEventStartTime().getTime()) {
								operatorEventDetailsRepository.updateEventStarteOne(operatorEventDetails2.getId());
								operatorEventDetails2.setState(1);
							}
							// 如果活动开始时间大于当前时间--活动已开始
							if (date.getTime() >= operatorEventDetails2.getEventStartTime().getTime()) {
								operatorEventDetailsRepository.updateEventStateTwo(operatorEventDetails2.getId());
								operatorEventDetails2.setState(2);
							}
							// 如果活动结束时间大于当前时间--活动结束
							if (date.getTime() >= operatorEventDetails2.getEventEndTime().getTime()) {
								operatorEventDetailsRepository.updateEventEndTimeState(operatorEventDetails2.getId());
								operatorEventDetails2.setState(3);
							}
						}
					} else {
						// 如果活动开始时间小于当前时间--活动未开始
						if (date.getTime() <= operatorEventDetails2.getEventStartTime().getTime()) {
							operatorEventDetailsRepository.updateEventStarteOne(operatorEventDetails2.getId());
							operatorEventDetails2.setState(1);
						}
						// 如果活动开始时间大于当前时间--活动已开始
						if (date.getTime() >= operatorEventDetails2.getEventStartTime().getTime()) {
							operatorEventDetailsRepository.updateEventStateTwo(operatorEventDetails2.getId());
							operatorEventDetails2.setState(2);
						}
						// 如果活动结束时间大于当前时间--活动结束
						if (date.getTime() >= operatorEventDetails2.getEventEndTime().getTime()) {
							operatorEventDetailsRepository.updateEventEndTimeState(operatorEventDetails2.getId());
							operatorEventDetails2.setState(3);
						}
					}
				} else {
					operatorEventDetailsRepository.updateStateZore(operatorEventDetails2.getId());
					operatorEventDetails2.setState(0);
				}
			}*/
			
			if (operatorEventDetails.size() > 0) {
				for (OperatorEventDetails operatorEventDetails1 : operatorEventDetails) {
					if (operatorEventDetails1.getFounder() != null) {
						OperatorUser user = operatorUserRepository.findOne(operatorEventDetails1.getFounder());
						if (user != null) {
							operatorEventDetails1.setName(user.getName());
						}
					}
					if (operatorEventDetails1.getEventPlace() != null
							&& !operatorEventDetails1.getEventPlace().equals("")) {
						ProviderProvince providerProvince = providerProvinceRepository
								.findOne(operatorEventDetails1.getEventPlace());
						if (providerProvince != null) {
							operatorEventDetails1.setPname(providerProvince.getName());
						}
					}
					if (operatorEventDetails1.getEventCounty() != null
							&& !operatorEventDetails1.getEventCounty().equals("")) {
						ProvideCity findOne = provideCityRepository.findOne(operatorEventDetails1.getEventCounty());
						if (findOne.getName() != null) {
							operatorEventDetails1.setAname(findOne.getName());
						}
					}
				}
			}
			if (operatorEventDetails != null) {
				map.put("cuont", operatorEventDetails);
			}
		}
		manager.clear();// 分离内存中受EntityManager管理的实体bean，让VM进行垃圾回收
		return map;
	}

	public Map<String, Object> getAppAndIosAndPc(Integer eventType, Integer page, Integer size) {
		String sql = "SELECT s.event_title,s.event_pic_url,s.event_infor,s.event_start_time,s.event_place,s.state,s.founder,"
				+ "s.event_end_time,s.registration_channel,s.event_join_person_num,s.enrollment,s.weight,s.is_money,s.organizer,s.id,"
				+ "s.activity_type_id,s.event_type,s.signup_start_time,s.signup_end_time,s.max_purchase_restriction,s.min_purchase_restriction,"
				+ "s.unit_num,s.unit_price,s.luck_draw_type,s.luck_draw_num,s.luck_name,s.availability,s.release_time,s.event_url,s.event_county,"
				+ "s.event_detailed_address,s.registration_form_details,s.agree_or_not,c. NAME AS place_name,d. NAME AS city_name"
				+ " FROM t_operator_event_details s " + " LEFT JOIN t_provide_province c  ON s.event_place = c.id "
				+ " LEFT JOIN t_provide_city d ON s.event_county = d.id "
				+ "WHERE s.event_type = :eventType AND s.state <> 4 AND s.state <> 0 AND s.state <> 7 ORDER BY s.signup_start_time DESC";
		Query query = manager.createNativeQuery(sql, OperatorEventDetailss.class);
		Map<String, Object> map = new HashMap<>();
		int index = (page - 1) * size;// 计算开始的记录数
		query = query.setParameter("eventType", eventType);
		if (query.getResultList().size() != 0) {
			map.put("size", query.getResultList().size());
		}
		@SuppressWarnings("unchecked")
		List<OperatorEventDetailss> operatorEventDetails = query.setMaxResults(size).setFirstResult(index).getResultList();
		Long nowTime= new Date().getTime();//获取当前时间
		for (OperatorEventDetailss eventDetails : operatorEventDetails) {
		    Integer orgstate =eventDetails.getState();
		    // 0未发布 默认 状态  7是未生效  4 是已删除
		    //报名未开始   6  报名时间 不为空   于 当前时间  并且 原状态 是 未发布 0 状态 
			if(eventDetails.getSignupStartTime() !=null && eventDetails.getSignupStartTime().getTime()>nowTime && eventDetails.getReleaseTime().getTime()< nowTime && orgstate ==0){
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),6);
			}
			//报名中  5   报名时间 不为空    报名开始时间  <=当前时间  <结束时间   且 原状态为  报名未开始 6 状态 
			else if(eventDetails.getSignupStartTime() !=null && eventDetails.getSignupStartTime().getTime()<=nowTime && eventDetails.getSignupEndTime().getTime()>nowTime && orgstate== 6 ){
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),5);
			}
			//未开始   1 活动开始时间 不能为空       开始时间 > 当前时间      发布时间 <=现在时间   原状态 为 报名中 5 
			else if(eventDetails.getEventStartTime() !=null && eventDetails.getSignupStartTime() !=null && eventDetails.getEventStartTime().getTime() >nowTime && eventDetails.getSignupEndTime().getTime() <nowTime && eventDetails.getReleaseTime().getTime() <=nowTime && orgstate== 5  ){
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),1);
			}
			//未开始   1 活动开始时间 不能为空       开始时间 > 当前时间      发布时间 <=现在时间   原状态 为 0未发布
			else if(eventDetails.getEventStartTime() !=null   && eventDetails.getSignupStartTime() ==null && eventDetails.getEventStartTime().getTime() >nowTime && eventDetails.getReleaseTime().getTime() <=nowTime && orgstate== 0 ){
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),1);
			}
			//活动开始 2   活动开始时间 不能为空    活动开始时间<= 当前时间 <结束时间    且 原状态 为 未开始 1 状态 
			else if(eventDetails.getEventStartTime() !=null && eventDetails.getEventStartTime().getTime()<=nowTime && eventDetails.getEventEndTime().getTime()>nowTime &&(orgstate==1 )){
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),2);
			}
			//活动结束 3   活动结束 时间 不能为空    活动结束 时间 < 当前时间   且 原状态 为 开始2  状态 
			else if(eventDetails.getEventEndTime() !=null && eventDetails.getEventEndTime().getTime()< nowTime &&(orgstate==2)){
				operatorEventDetailsRepository.updateStateByid(eventDetails.getId(),3);
			}
			/*
			// 如果未点击是否生效就修改活动状态为为生效状态
			if (operatorEventDetails2.getAvailability() == 0) {
				operatorEventDetails2.setState(7);
			} else {
				// 如果当前时间大于等于发布时间就修改活动状态
				if (date.getTime() >= operatorEventDetails2.getReleaseTime().getTime()) {
					if (!operatorEventDetails2.getActivityTypeId().equals("抽奖")) {

						// 当前时间小于活动活动报名时间 -- 报名未开始
						if (date.getTime() < operatorEventDetails2.getSignupStartTime().getTime()) {
							operatorEventDetails2.setState(6);
						}

						// 当前时间大于等于活动活动报名时间 -- 报名开始
						if (date.getTime() >= operatorEventDetails2.getSignupStartTime().getTime()) {
							operatorEventDetails2.setState(5);
						}

						// 当前时间大于活动报名时间 如果活动开始时间小于当前时间--活动未开始
						if (date.getTime() >= operatorEventDetails2.getSignupEndTime().getTime()
								&& date.getTime() <= operatorEventDetails2.getEventStartTime().getTime()) {
							operatorEventDetails2.setState(1);
						}
						// 如果活动开始时间大于当前时间--活动已开始
						if (date.getTime() >= operatorEventDetails2.getSignupEndTime().getTime()
								&& date.getTime() >= operatorEventDetails2.getEventStartTime().getTime()) {
							operatorEventDetails2.setState(2);
						}
						// 如果活动结束时间大于当前时间--活动结束
						if (date.getTime() >= operatorEventDetails2.getSignupEndTime().getTime()
								&& date.getTime() >= operatorEventDetails2.getEventEndTime().getTime()) {
							operatorEventDetails2.setState(3);
						}
					} else {
						// 如果活动开始时间小于当前时间--活动未开始
						if (date.getTime() <= operatorEventDetails2.getEventStartTime().getTime()) {
							operatorEventDetails2.setState(1);
						}
						// 如果活动开始时间大于当前时间--活动已开始
						if (date.getTime() >= operatorEventDetails2.getEventStartTime().getTime()) {
							operatorEventDetails2.setState(2);
						}
						// 如果活动结束时间大于当前时间--活动结束
						if (date.getTime() >= operatorEventDetails2.getEventEndTime().getTime()) {
							operatorEventDetails2.setState(3);
						}
					}
				} else {
					operatorEventDetails2.setState(0);
				}
			}
		*/
			}
		if (operatorEventDetails != null) {
			map.put("cuont", operatorEventDetails);
		}
		manager.clear();// 分离内存中受EntityManager管理的实体bean，让VM进行垃圾回收
		return map;
	}

	// 根据活动标题查询
	@SuppressWarnings("unchecked")
	public Map<String, Object> LikeSelect(String eventTitle, Integer eventType, Integer page, Integer size) {
		String jpql = "select s from OperatorEventDetails s where s.eventType =:eventType and s.eventTitle like CONCAT('%',:eventTitle,'%') and s.state <>  4  order by s.weight asc";
		Query query = manager.createQuery(jpql);
		Map<String, Object> map = new HashMap<>();
		int index = (page - 1) * size;// 计算开始的记录数
		query = query.setParameter("eventType", eventType).setParameter("eventTitle", eventTitle);

		if (query.getResultList().size() != 0) {
			map.put("size", query.getResultList().size());
		}

		List<OperatorEventDetails> enlistlist = query.setMaxResults(size).setFirstResult(index).getResultList();
		if (enlistlist.size() > 0) {
			for (OperatorEventDetails OperatorEventDetails : enlistlist) {
				if (OperatorEventDetails.getFounder() != null) {
					OperatorUser user = operatorUserRepository.findOne(OperatorEventDetails.getFounder());
					if (user != null) {
						OperatorEventDetails.setName(user.getName());
					}
				}
				if (OperatorEventDetails.getEventPlace() != null && !OperatorEventDetails.getEventPlace().equals("")) {
					ProviderProvince providerProvince = providerProvinceRepository
							.findOne(OperatorEventDetails.getEventPlace());
					if (providerProvince != null) {
						OperatorEventDetails.setPname(providerProvince.getName());
					}
				}
				if (OperatorEventDetails.getEventCounty() != null
						&& !OperatorEventDetails.getEventCounty().equals("")) {
					ProvideCity ProvideCity = provideCityRepository.findOne(OperatorEventDetails.getEventCounty());
					if (ProvideCity.getName() != null) {
						OperatorEventDetails.setAname(ProvideCity.getName());
					}
				}
			}
		}
		map.put("cuont", enlistlist);
		manager.clear();
		return map;
	}

	// 多条件查询
	@SuppressWarnings("unchecked")
	public Map<String, Object> multipleConditionQuery(Integer eventType, String eventTitle, Integer state,
			String founder, Integer isMoney, String stratTime, String endTime, Integer page, Integer size) {
		String jpql = "select s from OperatorEventDetails s, OperatorUser u where 1 = 1 and s.founder = u.id  and s.state <> 4  ";
		if (eventType != null && !eventType.equals("")) {
			jpql += " and s.eventType='" + eventType + "' ";
		}
		if (eventTitle != null && !eventTitle.equals("")) {
			jpql += " and s.eventTitle like'%" + eventTitle + "%' ";
		}
		if (state != null && !state.equals("")) {
			jpql += " and s.state='" + state + "' ";
		}
		if (founder != null && !founder.equals("")) {
			jpql += " and u.name like'%" + founder + "%' ";
		}
		if (isMoney != null) {
			jpql += " and s.isMoney='" + isMoney + "' ";
		}
		if (stratTime != null && endTime != null) {

			jpql += " and s.eventStartTime >='" + stratTime + "' and s.eventEndTime <='" + endTime + "'";
		}
		if (stratTime != null && endTime == null) {
			jpql += " and s.eventStartTime>='" + stratTime + "'";
		}
		if (stratTime == null && endTime != null) {
			jpql += " and s.eventEndTime<='" + endTime + "'";
		}
		if (true) {
			jpql += " order by s.weight asc";
		}
		if (page == null) {
			page = 1;
		}
		if (size == null) {
			size = 5;
		}

		int index = (page - 1) * size;
		Query createQuery = manager.createQuery(jpql);// 执行sql语句
		Map<String, Object> map = new HashMap<>();

		if (createQuery.getResultList().size() != 0) {
			map.put("size", createQuery.getResultList().size());
		}
		List<OperatorEventDetails> resultList = createQuery.setMaxResults(size).setFirstResult(index).getResultList();

		if (resultList.size() > 0) {
			for (OperatorEventDetails OperatorEventDetails : resultList) {
				if (OperatorEventDetails.getFounder() != null) {
					OperatorUser user = operatorUserRepository.findOne(OperatorEventDetails.getFounder());
					if (user != null) {
						OperatorEventDetails.setName(user.getName());
					}
				}
				if (OperatorEventDetails.getEventPlace() != null && !OperatorEventDetails.getEventPlace().equals("")) {
					ProviderProvince providerProvince = providerProvinceRepository
							.findOne(OperatorEventDetails.getEventPlace());
					if (providerProvince != null) {
						OperatorEventDetails.setPname(providerProvince.getName());
					}
				}
				if (OperatorEventDetails.getEventCounty() != null
						&& !OperatorEventDetails.getEventCounty().equals("")) {
					ProvideCity ProvideCity = provideCityRepository.findOne(OperatorEventDetails.getEventCounty());
					if (ProvideCity.getName() != null) {
						OperatorEventDetails.setAname(ProvideCity.getName());
					}
				}
			}
		}
		map.put("cuont", resultList);
		manager.clear();
		return map;
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> getEventUser(String id, String activityTypeId, Integer page, Integer size) {
		Map<String, Object> map = new HashMap<>();
		if (!activityTypeId.equals("抽奖")) {
			String jpql = "select e from OperatorActivityEnlist e where e.activityId = :id and e.state = 1";
			Query query = manager.createQuery(jpql);
			int index = (page - 1) * size;// 计算开始的记录数
			query = query.setParameter("id", id);

			if (query.getResultList().size() != 0) {
				map.put("size", query.getResultList().size());
			}
			List<OperatorActivityEnlist> enlistlist = query.setMaxResults(size).setFirstResult(index).getResultList();
			if (enlistlist.size() > 0) {
				for (OperatorActivityEnlist operatorActivityEnlist : enlistlist) {
					PersonalUser findOne = personalUserRepository.findOne(operatorActivityEnlist.getUserId());
					if (findOne != null) {
						operatorActivityEnlist.setUserId(findOne.getUsername());
					}
				}
			}
			map.put("cuont", enlistlist);
		} else {
		String sql = "SELECT a.id,a.luckdraw_type,a.record_time,tpu.username as user_tele,tpa.`name` as user_name,tpa.address FROM t_operator_luckdraw_record a , t_personal_user  tpu,  t_personal_address tpa WHERE a.user_id=tpu.id AND tpa.user_id = a.user_id AND tpa.isdefault = 1 AND a.activity_id =:id ORDER BY a.record_time DESC  ";
		Query query = manager.createNativeQuery(sql, LuckdrawRecordMove.class);
		int index = (page - 1) * size;
		query = query.setParameter("id", id);
		if (query.getResultList().size() != 0) {
			map.put("size", query.getResultList().size());
			List<LuckdrawRecordMove> enlist = (List<LuckdrawRecordMove>) query.setMaxResults(size).setFirstResult(index).getResultList();
			map.put("cuont", enlist);
		}
		if(query.getResultList().size() == 0){
			map.put("size", 0);
			map.put("cuont", null);
		}
			/*
			String jpql = "select d from OperatorLuckdrawRecord d where d.activityId = :id ORDER BY d.recordTime desc";
			Query query = manager.createQuery(jpql);
			int index = (page - 1) * size;// 计算开始的记录数
			query = query.setParameter("id", id);
			if (query.getResultList().size() != 0) {
				map.put("size", query.getResultList().size());
			}
			List<OperatorLuckdrawRecord> resultList = query.setMaxResults(size).setFirstResult(index).getResultList();
			map.put("cuont", resultList);

			if (resultList.size() > 0) {
				for (OperatorLuckdrawRecord operatorLuckdrawRecord : resultList) {
					PersonalUser findOne = personalUserRepository.findOne(operatorLuckdrawRecord.getUserId());
					if (findOne != null) {
						operatorLuckdrawRecord.setUserId(findOne.getUsername());
					}
				}

			}
		*/}
		manager.clear();
		return map;
	}

	@SuppressWarnings("unchecked")
	public Map<String, Object> getEventDetailsOfApplicants(String id, String activityTypeId) {
		Map<String, Object> map = new HashMap<>();
		if (!activityTypeId.equals("抽奖")) {
			String jpql = "select e from OperatorActivityEnlist e where e.activityId = :id and e.state = 1";
			Query query = manager.createQuery(jpql);
			query = query.setParameter("id", id);

			List<OperatorActivityEnlist> enlistlist = query.getResultList();
			if (enlistlist.size() > 0) {
				for (OperatorActivityEnlist operatorActivityEnlist : enlistlist) {
					PersonalUser findOne = personalUserRepository.findOne(operatorActivityEnlist.getUserId());
					if (findOne != null) {
						operatorActivityEnlist.setUserId(findOne.getUsername());
					}
				}
			}
			map.put("cuont", enlistlist);
		} else {
			String sql = "SELECT a.id,a.luckdraw_type,a.record_time,tpu.username as user_tele,tpa.`name` as user_name,tpa.address FROM t_operator_luckdraw_record a , t_personal_user  tpu,  t_personal_address tpa WHERE a.user_id=tpu.id AND tpa.user_id = a.user_id AND tpa.isdefault = 1 AND a.activity_id =:id ORDER BY a.record_time DESC  ";
			Query query = manager.createNativeQuery(sql, LuckdrawRecordMove.class);
			query = query.setParameter("id", id);
			if (query.getResultList().size() != 0) {
				List<LuckdrawRecordMove> enlist = (List<LuckdrawRecordMove>) query.getResultList();
				map.put("cuont", enlist);
			}
			/*
			String jpql = "select d from OperatorLuckdrawRecord d where d.activityId = :id ORDER BY d.recordTime desc";
			Query query = manager.createQuery(jpql);
			query = query.setParameter("id", id);

			List<OperatorLuckdrawRecord> resultList = query.getResultList();
			map.put("cuont", resultList);
			if (resultList.size() > 0) {
				for (OperatorLuckdrawRecord operatorLuckdrawRecord : resultList) {
					PersonalUser findOne = personalUserRepository.findOne(operatorLuckdrawRecord.getUserId());
					if (findOne != null) {
						operatorLuckdrawRecord.setUserId(findOne.getUsername());
					}
				}

			}
		*/}
		manager.clear();
		return map;
	}

	public Boolean theQueryActivityTitleIsRepeated(String eventTitle) {
		String jpql = "select s from OperatorEventDetails s where s.eventTitle = :eventTitle and s.state <> 4";
		Query query = manager.createQuery(jpql);
		query = query.setParameter("eventTitle", eventTitle);
		int size = query.getResultList().size();
		if (size == 0) {
			return true;// 没有查询到
		} else {
			return false;// 查询到了
		}
	}
	
	public String selectSecckillEventDetails(){
		// 查询当天
		String sql = "SELECT oed.id FROM t_operator_event_details oed WHERE oed.activity_type_id = '秒杀'  AND oed.state!=4 AND oed.availability = 1 and oed.event_start_time <=NOW() and oed.event_end_time >=NOW() ORDER BY oed.event_start_time desc LIMIT 0,1";
		Query query = manager.createNativeQuery(sql, EventDetailsMove.class);
		if (query.getResultList().size()!=0) {
			EventDetailsMove enlist = (EventDetailsMove) query.getSingleResult();
			String activityId = enlist.getId();
			return activityId;
		}
		if (query.getResultList().size()==0) {
			// 查询以后活动
			sql = "SELECT oed.id FROM t_operator_event_details oed WHERE oed.activity_type_id = '秒杀' AND oed.state!=4 AND oed.availability = 1 and oed.event_start_time >=NOW() ORDER BY oed.event_start_time asc LIMIT 0,1";
			query = manager.createNativeQuery(sql, EventDetailsMove.class);
			if (query.getResultList().size()!=0) {
				EventDetailsMove	enlist = (EventDetailsMove) query.getSingleResult();
				String activityId = enlist.getId();
				return activityId;
			}
			//查询以前
			if (query.getResultList().size()==0) {
				sql = "SELECT oed.id FROM t_operator_event_details oed WHERE oed.activity_type_id = '秒杀' AND oed.state!=4 AND oed.availability = 1 and oed.event_start_time <=NOW() ORDER BY oed.event_start_time desc LIMIT 0,1";
				query = manager.createNativeQuery(sql, EventDetailsMove.class);
				EventDetailsMove enlist = (EventDetailsMove) query.getSingleResult();
				if (query.getResultList().size()!=0) {
					String activityId = enlist.getId();
					return activityId;
				}
			}
		}
		return null;
	}
}
